package com.swak.fx.support;

import java.util.concurrent.CompletableFuture;

import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.stage.Stage;

/**
 * 启动页
 * 
 * @author 618lf
 */
public class Splash extends Window {

	protected volatile Thread thread;
	protected volatile int times;
	protected volatile boolean finish;

	public Splash(Stage stage, int adjust) {
		super(stage, adjust);
	}

	@Override
	public void initializeParts() {
		super.initializeParts();
		this.start();
	}

	@Override
	public void initializeFinish() {
		super.initializeFinish();
	}

	protected void start() {
		this.startApp();
		this.startProgress();
	}

	/**
	 * 启动服务
	 */
	protected void startApp() {
		AbstractApplication.INSTANCE.startApp();
	}

	/**
	 * 启动服务的进度
	 */
	protected void startProgress() {
		this.finish = false;
		this.times = 0;
		this.progressProperty.set(0);
		this.thread = new Thread(() -> {
			try {
				while (!finish) {
					double selection = this.progressProperty.get();
					if (selection <= 0.5) {
						this.progressProperty.set(selection + 0.05);
					} else if (selection <= 0.75) {
						times++;
						if (times >= 5) {
							this.progressProperty.set(selection + 0.03);
							times = 0;
						}
					} else if (selection <= 0.95) {
						times++;
						if (times >= 10) {
							this.progressProperty.set(selection + 0.01);
							times = 0;
						}
					}
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						break;
					}
				}
				this.progressProperty.set(1);
				this.finish = true;
				try {
					Thread.sleep(200);
				} catch (Exception e) {
				}
			} finally {
				this.closeFuture.complete(null);
			}
		});
		this.thread.setName("UI.Splash");
		this.thread.setDaemon(true);
		this.thread.start();
	}

	private void finishProgress() {
		try {
			if (thread != null && !thread.isInterrupted()) {
				thread.interrupt();
			} else {
				finish = true;
			}
		} catch (Throwable e) {
			finish = true;
		}
	}

	@Override
	public CompletableFuture<Void> waitClose() {
		return initFuture.thenCompose((v) -> {
			this.finishProgress();
			return closeFuture;
		});
	}

	// ================================================================================
	// 进度属性
	// ================================================================================
	private DoubleProperty progressProperty = new SimpleDoubleProperty(0);

	public DoubleProperty progressProperty() {
		return progressProperty;
	}
}